package com.lhuc.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lhucstart
 * @create 2021-06-24 20:09
 */

@RestController
public class FileUploadController {

    @Value(value = "${file.path}")
    private String path;


    public static List<String> getFiles(String path) {
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
                //文件名，不包含路径
                //String fileName = tempList[i].getName();
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了，
            }
        }
        return files;
    }


    @RequestMapping(value = "zipDownload", method = RequestMethod.GET)
    public String zipDownload(HttpServletRequest request, HttpServletResponse response) {

        List<String> pathList = getFiles(path);

        List<File> files = new ArrayList<>();

        if(!pathList.isEmpty()){

            pathList.forEach(str -> files.add(new File(str)));
        }


        if(files.isEmpty()){
            return "files isEmpty";
        }


        ZipDownloadUtil.zipDownload(response, "demo.zip", files);
        return "download success";
    }

}

